﻿using System;
using System.Collections.Generic;
using KillBill.Business.Entities;
using KillBill.Common.View;
using KillBill.Presentation.Common;
using KillBill.Presentation.Modules.Administration.View;
using KillBill.Presentation.Modules.Sales.IView;
using KillBill.Presentation.Modules.Sales.ProductsServiceReference;
using KillBill.Presentation.Modules.Sales.AdministrationServiceReference;
using KillBill.Presentation.Modules.Sales.SalesServiceReference;


namespace KillBill.Presentation.Modules.Sales.Presenter
{
    public class BillingPresenter
    {
        private readonly ProductsServiceClient _productsService = new ProductsServiceClient();
        private readonly SalesServiceClient _salesService = new SalesServiceClient();
        private readonly AdministrationServiceClient _administrationService = new AdministrationServiceClient();
        private readonly string _sessionId;
        private readonly string _employeeId;
        private bool _flagCustomerFound = false;

        public Customer Customer { get; set; }
        public IBilling View { get; set; }
        public BillingPresenter(IBilling view)
        {
            View = view;
            _sessionId = Context.SessionID;
            _employeeId = Context.EmployeeID;
        }
        public void GetCustomerData()
        {
            try
            {
                _flagCustomerFound = true;
                Customer = _administrationService.FindCustomer(View.UserId, _sessionId);
                if (Customer.CustomerID == null)
                {
                    var customerAddEditView = new CustomerAddEditView();
                    customerAddEditView.ShowDialog();
                    Customer = customerAddEditView.Customer;
                    _flagCustomerFound = false;
                }
                View.UserId = Customer.CustomerID;
                View.UserName = Customer.Person.FirstName + " " + Customer.Person.LastName;
                View.UserAddress = Customer.Person.Address;
                View.UserPhone = Customer.Person.Phone;
            }
            catch (Exception)
            {
                View.ShowConnectionErrorMessage("Facturación");
            }
        }
        public void GetProducts()
        {
            try
            {
                var products = _productsService.FindProduct(View.ProductSearchValue, Context.SessionID);
                if (products.Success)
                {
                    View.Products = products.Products;
                }
                else
                    if (products.Messages.Count > 0)
                        View.ShowMessage(products.Messages[0]);
            }
            catch (Exception)
            {
                View.ShowConnectionErrorMessage("Facturación");
            }
        }
        public void AddProductToDetail()
        {
            if (View.SelectedObject.Stock > View.DetailCuantity)
            {
                View.SubTotal = 0;
                View.Iva = 0;
                View.Ice = 0;

                if (View.Detail.ContainsKey(View.SelectedObject.ProductID.ToString()))
                    View.Detail[View.SelectedObject.ProductID.ToString()].Quantity += View.DetailCuantity;
                else
                    View.Detail.Add(View.SelectedObject.ProductID.ToString(), new Detail(View.DetailCuantity, View.SelectedObject));
                foreach (var detail in View.Detail)
                {
                    View.SubTotal += detail.Value.TotalValue;
                    View.Iva += (detail.Value.Product.IVAApplied) ? (detail.Value.TotalValue * (decimal)0.12) : 0;
                    View.Ice += ((decimal)detail.Value.Product.ICETax * detail.Value.TotalValue);
                }
                View.Total = View.SubTotal + View.Iva + View.Ice;
            }
            else
            {
                View.ShowMessage("Advertencia", "No existen suficientes existencias del producto seleccionado",
                                 MessageOptions.Ok, MessageIcon.Exclamation);
            }
            View.Detail = View.Detail;
        }
        public void SaveData()
        {
            var salesHeader = new SalesHeader();
            try
            {
                salesHeader.SubTotal = View.SubTotal;
                salesHeader.TaxAmount = View.Ice + View.Iva;
                salesHeader.CustomerID = Customer.CustomerID;
                salesHeader.EmployeeID = _employeeId;

                salesHeader.SalesDetail = new TrackableCollection<SalesDetail>();
                foreach (var detail in View.Detail)
                {
                    var salesDetail = new SalesDetail
                                          {
                                              ProductID = detail.Value.Product.ProductID,
                                              OrderQty = detail.Value.Quantity,
                                              UnitPrice = detail.Value.Product.LastPrice
                                          };
                    salesHeader.SalesDetail.Add(salesDetail);
                }
                salesHeader = _salesService.RegisterSale(salesHeader, _sessionId);
                if (salesHeader.Messages.Count > 0)
                    View.ShowMessage("Facturación", salesHeader.Messages[0], MessageOptions.Ok, (salesHeader.Success) ? MessageIcon.Information : MessageIcon.Exclamation);
                if (salesHeader.Success)
                {
                    BillingPrinter.PrintBill(salesHeader.SalesHeaderID, Customer.Person, View.Detail, View.SubTotal,
                                             View.Iva, View.Ice, View.Total);
                    ClearData();
                }
            }
            catch (Exception)
            {
                salesHeader.Success = false;
                View.ShowConnectionErrorMessage("Facturación");
            }
        }
        public void ClearData()
        {
            this.Customer = new Customer();
            View.Detail = new Dictionary<string, Detail>();
            View.DetailCuantity = 1;
            View.Ice = 0;
            View.Iva = 0;
            View.ProductSearchValue = "";
            View.SelectedObject = new Product();
            View.SubTotal = 0;
            View.Total = 0;
            View.UserAddress = "";
            View.UserId = "";
            View.UserName = "";
            View.UserPhone = "";
        }
        public void EditCustomer()
        {
            if (!_flagCustomerFound) return;
            var customerAddEditView = new CustomerAddEditView(Customer);
            customerAddEditView.ShowDialog();
            Customer = customerAddEditView.Customer;
        }
    }
}
